package com.herench.bs.transfer;

import com.herench.bs.transfer.Dialect;
import com.herench.bs.utils.DataFormatUtils;
import org.apache.cxf.endpoint.Client;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.*;

public class LoadAllClinicOrderListTransfer extends AbstractTransfer {
    public LoadAllClinicOrderListTransfer(String method, Client client,String messageMethod) {
        super(method, client,messageMethod);
    }
    @Override
    public String toInvokeMessage(Map<String, Object> params) throws Exception {
        String idCard = (String) params.get("idCard");
        String patientId = (String) params.get("patientId");
        String appointDate = DataFormatUtils.getSimpleTimeString((Date) params.get("appointDate"));
        String tranNo = (String) params.get("tranNo");
        String visitNo = (String) params.get("visitNo");
        Document tplDoc = getTplDoc(getMethod());
        Element dataRowElement = tplDoc.getRootElement().element("CommitData").addElement("Data").addElement("DataRow");
        dataRowElement.addAttribute("PERSON_NO", idCard).addAttribute("PATIENT_ID", patientId).addAttribute("VISIT_NO", visitNo).addAttribute("VISIT_DATE", appointDate).addAttribute("TRAN_NO", tranNo);
        return tplDoc.asXML();
    }
    @Override
    public Map<String, Object> toResultMessage(String resMsg) throws Exception {
        Map<String, Object> res = new HashMap<>(16);
        Document document = DocumentHelper.parseText(resMsg);
        Element resultInfo = document.getRootElement().element("Result").element("Info");
        String executeStatus = resultInfo.attributeValue("EXECUTE_STATUS");
        String executeMessage = resultInfo.attributeValue("EXECUTE_MESSAGE");
        List<Map<String, Object>> appNoList = new ArrayList<>();
        /**
         * 根据就诊记录获取所有缴费记录信息
         */
        if (Dialect.getSuccessfulState().equals(executeStatus)) {
            List<Element> dataRow = document.getRootElement().element("ReturnData").element("Data").elements();
            for (Element element : dataRow) {
                LoadAllClinicOrderListTransfer.LoadAllClinicOrderListInnerMessage innerMessage = new LoadAllClinicOrderListTransfer.LoadAllClinicOrderListInnerMessage(element);
                Map<String, Object> subAppNoMap = new HashMap<>(16);
                subAppNoMap.put("paySeq", innerMessage.getAppNo());
                subAppNoMap.put("totalCost", innerMessage.getCharges());
                subAppNoMap.put("costTypeName", innerMessage.getReqClass());
                subAppNoMap.put("inputDateTime", innerMessage.getInputDateTime().replace('/', '-'));
                subAppNoMap.put("status",innerMessage.getStatus());//0 未收费 ，1 已收费
//                    subAppNoMap.put("itemName",innerMessage.getItemName());
                subAppNoMap.put("patientId",innerMessage.getPatientId());
                subAppNoMap.put("docName",innerMessage.getOrderedDoctor());
                subAppNoMap.put("deptName",innerMessage.getOrderedByName());
                subAppNoMap.put("affirStatus",innerMessage.getAffirStatus());
                subAppNoMap.put("performedByName",innerMessage.getPerformedByName());
                if (innerMessage.getStatus().equals("0")){
                    subAppNoMap.put("statusName","");
                }
                if (innerMessage.getStatus().equals("1")){
                    if(innerMessage.getReqClass().equals("检查")||innerMessage.getReqClass().equals("检验")||innerMessage.getReqClass().equals("其他")){
                        if(innerMessage.getAffirStatus().equals("1")){
                            subAppNoMap.put("statusName","已执行");
                        }else {
                            subAppNoMap.put("statusName","未执行");
                        }
                    }
                    if(innerMessage.getReqClass().equals("处方")){
                        if(innerMessage.getAffirStatus().equals("1")){
                            subAppNoMap.put("statusName","已取药");
                        }else {
                            subAppNoMap.put("statusName","未取药");
                        }
                    }
                }
//                    appNoList.add(subAppNoMap);
                //flage=0;无重复处方号appNo
                String flag = "0";
                for (Map<String, Object> subMap : appNoList) {
                    if (subMap.get("paySeq").equals(innerMessage.getAppNo())) {
                        double getTotalCost = Double.parseDouble((String) subMap.get("totalCost"));
                        double innerTotalCost = Double.parseDouble(innerMessage.getCharges());
                        String totalCost = DataFormatUtils.getFormatMoney(getTotalCost + innerTotalCost);
                        String costTypeName = (String) subMap.get("costTypeName");
                        String costTypeNameList[] = costTypeName.split("\\+");
                        if (innerMessage.getStatus().equals("0")){
                            subMap.put("statusName","");
                        }
                        if (innerMessage.getStatus().equals("1")){
                            if(innerMessage.getReqClass().equals("检查")||innerMessage.getReqClass().equals("检验")||innerMessage.getReqClass().equals("其他")){
                                if(innerMessage.getAffirStatus().equals("1")){
                                    subMap.put("statusName","已执行");
                                }else {
                                    subMap.put("statusName","未执行");
                                }
                            }
                            if(innerMessage.getReqClass().equals("处方")){
                                if(innerMessage.getAffirStatus().equals("1")){
                                    subMap.put("statusName","已取药");
                                }else {
                                    subMap.put("statusName","未取药");
                                }
                            }
                        }
                        //0:没有重复的项目名
                        String ifIncluded = "0";
                        for (int i = 0; i < costTypeNameList.length; i++) {
                            if (costTypeNameList[i].equals(innerMessage.getReqClass())) {
                                //1:有重复的项目名
                                ifIncluded = "1";
                            }
                        }
                        if ("0".equals(ifIncluded)) {
                            subMap.put("costTypeName", costTypeName + "+" + innerMessage.getReqClass());
                        }
                        subMap.put("totalCost", totalCost);
                        subMap.put("performedByName", innerMessage.getPerformedByName());
                        subMap.put("inputDateTime", innerMessage.getInputDateTime().replace('/', '-'));
                        //flage=0;有重复处方号appNo
                        flag = "1";
                    }
                }
                if ("0".equals(flag)) {
                    appNoList.add(subAppNoMap);
                }
            }

        }
//            按照“inputDateTime”降序排序
        Collections.sort(appNoList, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Date a = null;
                Date b = null;
                try {
                    a = DataFormatUtils.parser((String) o1.get("inputDateTime"));
                    b = DataFormatUtils.parser((String) o2.get("inputDateTime"));
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("LoadAllClinicOrderListTransfer>>>toResultMessage>>>compare:inputDateTime日期格式转换失败！");
                }
                int compareRes = a.compareTo(b);
                return (compareRes < 0 ? 1 : (compareRes < 1 ? 0 : -1));
            }
        });
        res.put("appNoList", appNoList);
        res.put("code", executeStatus);
        res.put("message", executeMessage);

        return res;
    }
    public class LoadAllClinicOrderListInnerMessage implements InnerMessage {

        /**
         * 开单项目序号
         */
        private String clinicCostItemNo;
        /**
         * 患者ID
         */
        private String patientId;
        /**
         * 项目编码
         */
        private String itemCode;
        /**
         * 项目名称
         */
        private String itemName;
        /**
         * 项目规格
         */
        private String itemSpec;
        /**
         * 数量
         */
        private String amount;
        /**
         * 单位
         */
        private String units;
        /**
         * 开单科室代码
         */
        private String orderedBy;
        /**
         * 开单医师姓名
         */
        private String orderedDoctor;
        /**
         * 应收费用
         */
        private String costs;
        /**
         * 实收费用
         */
        private String charges;
        /**
         * 医嘱开立时间
         */
        private String inputDateTime;
        /**
         * 开单类别
         */
        private String reqClass;
        /**
         * 开单识别号
         */
        private String reqId;
        /**
         * 用法
         */
        private String admin;
        /**
         * 处方号
         */
        private String appNo;
        /**
         * 就诊ID，就诊日期YYYYMMDD+就诊号
         */
        private String clinicId;
        /**
         * 执行科室代码
         */
        private String performedBy;
        /**
         * 收费状态
         */
        private String status;
        /**
         * 统筹支付
         */
        private String insurPay;
        /**
         * 个人账户支付
         */
        private String accountPay;
        /**
         * 个人自费
         */
        private String ownPay;
        /**
         * 开单科室名称
         */
        private String orderedByName;
        /**
         * 执行科室名称
         */
        private String performedByName;
        /**
         * 取药窗口号
         */
        private String drugWinNo;
        /**
         * 执行状态
         */
        private String affirStatus;


        public String getClinicCostItemNo() {
            return clinicCostItemNo;
        }

        public String getPatientId() {
            return patientId;
        }

        public String getItemCode() {
            return itemCode;
        }

        public String getItemName() {
            return itemName;
        }

        public String getItemSpec() {
            return itemSpec;
        }

        public String getAmount() {
            return amount;
        }

        public String getUnits() {
            return units;
        }

        public String getOrderedBy() {
            return orderedBy;
        }

        public String getOrderedDoctor() {
            return orderedDoctor;
        }

        public String getCosts() {
            return costs;
        }

        public String getCharges() {
            return charges;
        }

        public String getInputDateTime() {
            return inputDateTime;
        }

        public String getReqClass() {
            return reqClass;
        }

        public String getReqId() {
            return reqId;
        }

        public String getAdmin() {
            return admin;
        }

        public String getAppNo() {
            return appNo;
        }

        public String getClinicId() {
            return clinicId;
        }

        public String getPerformedBy() {
            return performedBy;
        }

        public String getStatus() {
            return status;
        }

        public String getInsurPay() {
            return insurPay;
        }

        public String getAccountPay() {
            return accountPay;
        }

        public String getOwnPay() {
            return ownPay;
        }

        public String getOrderedByName() {
            return orderedByName;
        }

        public String getPerformedByName() {
            return performedByName;
        }

        public String getDrugWinNo() {
            return drugWinNo;
        }

        public String getAffirStatus() {
            return affirStatus;
        }

        public LoadAllClinicOrderListInnerMessage(Element element) {
            this.clinicCostItemNo = element.attributeValue("CLINIC_COST_ITEM_NO");
            this.patientId = element.attributeValue("PATIENT_ID");
            this.itemCode = element.attributeValue("ITEM_CODE");
            this.itemName = element.attributeValue("ITEM_NAME");
            this.itemSpec = element.attributeValue("ITEM_SPEC");
            this.amount = element.attributeValue("AMOUNT");
            this.units = element.attributeValue("UNITS");
            this.orderedBy = element.attributeValue("ORDERED_BY");
            this.orderedDoctor = element.attributeValue("ORDERED_DOCTOR");
            this.costs = element.attributeValue("COSTS");
            this.charges = element.attributeValue("CHARGES");
            this.inputDateTime = element.attributeValue("INPUT_DATE_TIME");
            this.reqClass = element.attributeValue("REQ_CLASS");
            this.reqId = element.attributeValue("REQ_ID");
            this.admin = element.attributeValue("ADMIN");
            this.appNo = element.attributeValue("APP_NO");
            this.clinicId = element.attributeValue("CLINIC_ID");
            this.performedBy = element.attributeValue("PERFORMED_BY");
            this.status = element.attributeValue("STATUS");
            this.insurPay = element.attributeValue("INSUR_PAY");
            this.accountPay = element.attributeValue("ACCOUNT_PAY");
            this.ownPay = element.attributeValue("OWN_PAY");
            this.orderedByName = element.attributeValue("ORDERED_BY_NAME");
            this.performedByName = element.attributeValue("PERFORMED_BY_NAME");
            this.drugWinNo = element.attributeValue("DRUG_WIN_NO");
            this.affirStatus = element.attributeValue("AFFIR_STATUS");
        }
    }

}
